/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/filter/CharacterEncodingFilter.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: CharacterEncodingFilter.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (周一, 02 七月 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.web.filters;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 编码过滤
 * 
 * @author elancom
 * @date 2012-6-15
 */
public class CharacterEncodingFilter extends OncePerRequestFilter {

	private String encoding = "UTF-8";

	private boolean forceEncoding = false;

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public void setForceEncoding(boolean forceEncoding) {
		this.forceEncoding = forceEncoding;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
	 * javax.servlet.FilterChain)
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

		if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
			request.setCharacterEncoding(this.encoding);
			if (this.forceEncoding) {
				response.setCharacterEncoding(this.encoding);
			}
		}

		p(request);

		filterChain.doFilter(request, response);
	}

	/**
	 * @param request
	 */
	private void p(HttpServletRequest request) {
		final HttpServletRequest r = (HttpServletRequest) request;
		final StringBuffer sb = new StringBuffer();
		sb.append("请求参数:" + r.getRequestURI().substring(r.getRequestURI().lastIndexOf("/"))).append("\n");
		@SuppressWarnings("unchecked")
		final Enumeration<String> ns = request.getParameterNames();
		sb.append("--------------------------------------------------------------------------").append("\n");
		while (ns.hasMoreElements()) {
			final String n = ns.nextElement();
			sb.append(n + "：" + request.getParameter(n)).append("\n");
		}
		sb.append("--------------------------------------------------------------------------").append("\n");
		System.out.println(sb);
	}
}
